<template>
  <!-- 选择要打印的文件 -->
  <view class="upload-file-template">
    <!-- <uni-file-picker
      v-model="fileList"
      ref="files"
      fileMediatype="all"
      :auto-upload="false"
      @select="select"
    >
      <view class="select-file"> 选择要上传的文件 </view>
    </uni-file-picker> -->

    <view class="select-file" @tap="selectFileHandle">
      <slot> 选择要上传的文件 </slot>
    </view>
    <!-- 用列表的方式显示预览的文件 -->
    <view class="file-list-view">
      <view
        class="file-item"
        v-for="(item, index) in selectFileList"
        :key="index"
      >
        <view class="file-up">
          <view class="file-name">{{ item.fileName }}</view>
          <view class="file-operation">
            <u-button
              type="primary"
              class="btn"
              size="mini"
              :hairline="true"
              text="上传"
              :disabled="item.isUploadComplete"
              @click="singleUploadFile(index)"
            ></u-button>
            <u-button
              type="primary"
              class="btn"
              size="mini"
              :hairline="true"
              text="预览"
              :disabled="!item.isUploadComplete"
              @click="viewFile(index)"
            ></u-button>
            <u-button
              type="error"
              class="btn"
              size="mini"
              :hairline="true"
              text="删除"
              @click="deleteFile(index)"
            >
            </u-button>
          </view>
        </view>
        <view class="file-down">
          <u-row>
            <u-col span="10">
              <u-line-progress
                :percentage="item.fileProgress"
                activeColor="#409EFF"
              ></u-line-progress>
            </u-col>
            <u-col span="2">
              <view class="file-status">{{ item.fileStatus }}</view>
            </u-col>
          </u-row>
        </view>
      </view>
    </view>
    <m-button @click="allUploadFile" style="margin-top: 20rpx"
      >上传文件</m-button
    >
    <u-modal
      :show="showModel"
      :title="title"
      :content="content"
      :closeOnClickOverlay="true"
      :showCancelButton="true"
      @cancel="cancelModel"
      @confirm="confirmModal"
    ></u-modal>
    <tki-file-manager ref="filemanager" @result="resultPath"></tki-file-manager>
  </view>
</template>
<script>
import Button from "../Button/index";
import tkiFileManager from "../tki-file-manager/tki-file-manager";

export default {
  name: "upload-file",
  components: {
    "m-button": Button,
    "tki-file-manager": tkiFileManager,
  },
  data() {
    return {
      fileList: [],
      showModel: false,
      title: "删除文件",
      content: "",
      deleteIndex: undefined,
      selectFileList: [],
    };
  },
  props: {
    uploadUrl: {
      type: String,
      default: "",
    },
    formData: {
      type: Object,
      default: {},
    },
    headers: {
      type: Object,
      default: {},
    },
  },
  methods: {
    /**
     * 上传单个文件
     * @param {Number} index 单个文件在selectFileList中的位置
     */
    singleUploadFile(index) {
      if (index < 0 || index >= this.selectFileList.length) return;
      const file = this.selectFileList[index];
      this.upload(file, index);
    },
    async upload(item, index) {
      const defaultFormData = {
        fileName: item.fileName,
        extname: item.extname,
      };
      const formData = Object.assign({}, defaultFormData, this.formData);
      this.selectFileList[index].fileStatus = "上传中...!";
      const uploadTask = uni.uploadFile({
        url: this.uploadUrl,
        filePath: item.path,
        formData,
        success: (uploadFileRes) => {
          let { data, statusCode } = uploadFileRes;
          //data 中携带已经转码好的文件路径 然后发送到kkFileView 中预览
          if (statusCode == 200) {
            this.selectFileList[index].isUploadComplete = true;
            data = JSON.parse(data);
            const { view_path, file_id } = data.data;
            const returnItem = {
              fileId: file_id,
              fileName: item.fileName,
            };
            item["viewPath"] = view_path;
            this.selectFileList[index].fileStatus = "上传成功!";
            //通知文件上传成功!
            this.fileIsReady = true;
            //this.fileUploadCompleted.push(item.name);
            this.$emit("uploadSuccess", returnItem);
            this.$forceUpdate();
          } else {
            this.selectFileList[index].fileStatus = "上传失败!";
            this.selectFileList[index].fileProgress = 0;
          }
        },
        fail: () => {
          this.selectFileList[index].fileStatus = "上传失败!";
        },
      });
      uploadTask.onProgressUpdate((res) => {
        const { progress } = res;
        this.$forceUpdate();
        this.selectFileList[index].fileProgress = progress;
      });
    },
    /**
     * 返回需要预览文件的viewPath路径
     */
    viewFile(index) {
      if (index < 0 || index >= this.selectFileList.length) return;
      const { viewPath } = this.selectFileList[index];
      this.$emit("viewFile", viewPath);
    },
    /**
     * 删除文件
     * @param {Number} index
     */
    deleteFile(index) {
      if (index < 0 || index >= this.selectFileList.length) return;
      const file = this.selectFileList[index];
      if (file.isUploadComplete) {
        this.content = `'${file.fileName}' 该文件已经上传,请确认是否删除?`;
      } else {
        this.content = `'${file.fileName}' 该文件未上传,请确认是否删除?`;
      }
      this.deleteIndex = index;
      this.showModel = true;
    },
    //关闭确认弹窗
    cancelModel() {
      this.showModel = false;
      this.deleteIndex = undefined;
      this.content = "";
    },
    //确认提交
    confirmModal() {
      this.selectFileList.splice(this.deleteIndex, 1);
      this.deleteIndex = undefined;
      this.showModel = false;
    },
    /**
     * 上传所有文件
     */
    allUploadFile() {
      this.selectFileList.forEach((element, index) => {
        this.selectFileList[index].fileStatus = "正在上传...";
        this.upload(element, index);
      });
    },
    selectFileHandle() {
      this.$refs.filemanager._openFile();
    },
    resultPath(e) {
      if (!e || typeof e != "string") {
        uni.showToast({
          title: "选择的文件不存在,请重新选择!",
          duration: 2000,
        });
        return;
      }
      let item = {};
      const paths = e.split("/");
      const length = paths.length;
      if (length <= 0) {
        uni.showToast({
          title: "选择的文件错误,请重新选择!",
          duration: 2000,
        });
        return;
      }
      item["fileName"] = paths[length - 1];
      const pos = item["fileName"].indexOf(".");
      if (pos == 1) {
        uni.showToast({
          title: "选择的文件错误,请重新选择!",
          duration: 2000,
        });
        return;
      }
      const extname = item["fileName"].substring(pos, item["fileName"].length);
      item["extname"] = extname;
      item["path"] = e;
      item["isUploadComplete"] = false;
      item["fileProgress"] = 0;
      item["fileStatus"] = "待上传...";
      this.selectFileList.push(item);
    },
  },
};
</script>
<style lang="scss">
.upload-file-template {
  margin: $uni-spacing-row-base;
  box-sizing: border-box;
  margin-top: 200rpx;

  .select-file {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100px;
    border: 1px dashed #dcdfe6;
    color: #909399;
    text-align: center;
    font-size: 18px;
    border-radius: 20rpx;
  }

  /deep/ .uni-file-picker__files .uni-file-picker__lists {
    display: none;
  }

  .file-list-view {
    .file-item {
      margin-bottom: $uni-spacing-col-base;
      border-bottom: 1px dashed #dcdfe6;
      padding-bottom: $uni-spacing-row-sm;
      margin-top: 20rpx;
      color: #909399;

      .file-up {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: $uni-spacing-col-base;

        .file-name {
          width: calc(100% - 350rpx);
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .file-operation {
          display: flex;
          justify-content: flex-start;

          /deep/ .u-button {
            margin-right: $uni-spacing-col-sm;
          }
        }
      }

      .file-status {
        font-size: 24rpx;
        text-align: center;
      }
    }

    .file-item:last-child {
      border-bottom: none;
    }
  }

  .btn {
    margin: 0 10rpx;
  }
}
</style>
